package com.tritrees.easygridview.widget;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Utils {
	public final static short _ACCOUNT_TYPE_UNKNOWN=0;
	public final static short _ACCOUNT_TYPE_CONSUMER=1;
	public final static short _ACCOUNT_TYPE_OPERATOR=2;
	public final static short _ACCOUNT_TYPE_SYSTEM=3;
	public final static byte[] _writeLock = new byte[0];//sqlite写锁标志־
	public final static byte[] _netaxLock = new byte[0];//netax地域服务器访问锁标志
	public final static String   SAVENAME="saveuser";
	public static int getScreenWidth(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getWidth();
	}

	public static int getScreenHeight(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getHeight();
	}

	public static float getScreenDensity(Context context) {
		try {
			DisplayMetrics dm = new DisplayMetrics();
			WindowManager manager = (WindowManager) context
					.getSystemService(Context.WINDOW_SERVICE);
			manager.getDefaultDisplay().getMetrics(dm);
			return dm.density;
		} catch (Exception ex) {

		}
		return 1.0f;
	}
	public static String UniBytesToString(byte[] bValue) throws IOException 
	{
		String sTemp;
		byte[] bTemp;
		
		bTemp=new byte[bValue.length+2];
		bTemp[0]=-1;
		bTemp[1]=-2;

		for (int i=0;i<bValue.length;i++)
		{
			bTemp[2+i]=bValue[i];
		}
		
		sTemp=new String(bTemp,"Unicode").trim();
		
		return sTemp;
	}
	private static final char[] alphatable =
		{
		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
		'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
		};
	private  final static int[] table = new int[]{
		45217, 45253, 45761, 46318, 46826,
		47010, 47297, 47614, 47614, 48119,
		49062, 49324, 49896, 50371, 50614,
		50622, 50906, 51387, 51446, 52218,
		52218, 52218, 52698, 52980, 53689, 54481, 55289};
	/**

     *  �����ַ�, �õ������ĸ, Ӣ����ĸ���ض�Ӧ�Ĵ�д��ĸ ����Ǽ��庺�ַ��� '*'

     */

	public static char Char2Alpha(char ch) 
	{
		if (ch >= 'a' && ch <= 'z')
		return (char) (ch - 'a' + 'A');
		if (ch >= 'A' && ch <= 'Z')
		return ch;
		int gb = gbValue(ch);
		if (gb < table[0])
		return '*';
		for(int i = 0; i < 26; ++i){
		if(match(i, gb)){
		if(i >= 26)
		return '*';
		else
		return alphatable[i];
		}
		}
		return '*';
	}
	/**

     * ���һ�����ֵ��ַ���һ������ƴ������ĸ���ַ�

     */
	public static String String2Alpha(String str) 
	{
		String Result = "";
		try {
			for (int i = 0; i < str.length(); i++) {
			Result += Char2Alpha(str.charAt(i));
		}
		} catch (Exception e) {
			Result = " ";
		}
		return Result;
	}
	private static boolean match(int i, int gb) 
	{
		if (gb < table[i])
		return false;
		int j = i + 1;
		//��ĸZʹ����������ǩ
		while (j < 26 && (table[j] == table[i]))
		++j;
		if (j == 26)
		return gb <= table[j];
		else
		return gb < table[j];
	}
	
/**

     * ȡ�����뺺�ֵı���

     */
	private static int gbValue(char ch) 
	{
		String str = new String();
		str += ch;
		try {
		byte[] bytes = str.getBytes("GB2312");
		if (bytes.length < 2)
		return 0;
		return (bytes[0] << 8 & 0xff00) + (bytes[1] & 0xff);
		} catch (Exception e) {
		return '*';
		}
	}
	


	public static String gbEncoding( final String gbString ) 
	{
		char[] utfBytes = gbString.toCharArray();
		String unicodeBytes = "";
		for( int byteIndex = 0; byteIndex < utfBytes.length; byteIndex ++ ) {
			String hexB = Integer.toHexString( utfBytes[ byteIndex ] );
			
			if( hexB.length() <= 2 ) {
				hexB = "00"+hexB;
			}
			unicodeBytes = unicodeBytes  + hexB;
		}
		System.out.println( "unicodeBytes is: " + unicodeBytes );
		return unicodeBytes;
	}
	public  static void setListViewHeightBasedOnChildren(ListView listView) {
        //��ȡListView��Ӧ��Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
               return;
        }
       
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {   //listAdapter.getCount()������������Ŀ
               View listItem = listAdapter.getView(i, null, listView);
               listItem.measure(0, 0);  //��������View �Ŀ��
               totalHeight += listItem.getMeasuredHeight();  //ͳ������������ܸ߶�
        }
       
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        //listView.getDividerHeight()��ȡ�����ָ���ռ�õĸ߶�
        //params.height���õ����ListView������ʾ��Ҫ�ĸ߶�
        listView.setLayoutParams(params);
	}
	//
	
	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	 
    public static byte[] getBytesFromObject(Serializable obj) throws Exception {
        if (obj == null) {
            return null;
        }
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(obj);
        return bo.toByteArray();
    }
    public static String getDate(int iDate) throws ParseException
    {
    	  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    	  Date currentTime=new Date();  //将截取到的时间字符串转化为时间格式的字符串 
    	  Date beginTime=sdf.parse("2013-01-01 00:00:00");  
    	  long intverval=(long)iDate*1000+beginTime.getTime();
    	 // system.
    	  String s = sdf.format(intverval);
    	  return s;

    	  
    }
    //将截取到的时间字符串转化为时间格式的字符串
    public static int getTime() throws ParseException
    {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  	  	Date currentTime=new Date();   
  	  	Date beginTime=sdf.parse("2013-01-01 00:00:00");  
  	  	long intverval=currentTime.getTime()-beginTime.getTime();
  	  	int time=(int) (intverval/1000);
  	  	return time;
    }

 
   
    public static void print(String strTag,String strMsg)
    {
    	Log.i(strTag, strMsg);
    }

    /**
     * Drawable转为Bitmap
     * 
     * @param drawable
     * @return bitmap
     * */
    public static Bitmap drawableToBitmap(Drawable drawable)
    {

        Bitmap bitmap = Bitmap
                .createBitmap(
                        drawable.getIntrinsicWidth(),
                        drawable.getIntrinsicHeight(),
                        drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        // canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }
    
    
    /**
     * 将图像裁剪成圆形
     * 
     * @param bitmap
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap)
    {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height)
        {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else
        {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right,
                (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top,
                (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);

        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }

	/**
	 * 合成多张图片
	 * 
	 * @param width
	 * @param grap
	 * @param bitmaps
	 * @return
	 */
	public static Bitmap combineImage(int width, int grap,
			ArrayList<Bitmap> bitmaps)
	{
		Bitmap itemBitmap;
		int itemWidth = (width - grap) / 2;
		Bitmap bitmap = Bitmap.createBitmap(width, width, Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setColor(Color.WHITE);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		Bitmap scaledBitmap = null;
		int num = bitmaps.size();
		if (num == 2)
		{
			for (int i = 0; i < num; i++)
			{
				itemBitmap = bitmaps.get(i);
				scaledBitmap = Bitmap.createScaledBitmap(itemBitmap, itemWidth,
						width, true);
				canvas.drawBitmap(scaledBitmap, (itemWidth + grap) * i, 0,
						null);
			}
		} else if (num == 3)
		{

			itemBitmap = bitmaps.get(0);
			scaledBitmap = Bitmap.createScaledBitmap(itemBitmap, itemWidth,
					width, true);
			canvas.drawBitmap(scaledBitmap, 0, 0, null);
			
			itemBitmap = bitmaps.get(1);
			scaledBitmap = Bitmap.createScaledBitmap(itemBitmap, itemWidth,
					itemWidth, true);
			canvas.drawBitmap(scaledBitmap, itemWidth + grap, 0, null);
			
			itemBitmap = bitmaps.get(1);
			scaledBitmap = Bitmap.createScaledBitmap(itemBitmap, itemWidth,
					itemWidth, true);
			canvas.drawBitmap(scaledBitmap, itemWidth + grap, itemWidth + grap, null);
		} else if (num == 4)
		{
			for (int i = 0; i < num; i++)
			{
				
				itemBitmap = bitmaps.get(i);
				scaledBitmap = Bitmap.createScaledBitmap(itemBitmap, itemWidth,
						itemWidth, true);
				if(i%2 == 0)
				{
					canvas.drawBitmap(scaledBitmap, 0, (itemWidth + grap) * (i/2),
							null);
				}else if(i%2 == 1){
					canvas.drawBitmap(scaledBitmap, itemWidth + grap, (itemWidth + grap) * (i/2),
							null);
				}
			}
		}

		return bitmap;
	}
}
